package com.example.sys.attachment.service.impl;

import cn.hutool.core.io.FileUtil;
import com.example.core.utils.IdGenerator;
import com.example.core.utils.SpringBeanUtils;
import com.example.core.utils.StringUtils;
import com.example.sys.attachment.service.SysFileService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/***
 *
 * 本地磁盘文件保存
 */
public class SysFileLocalServiceImpl implements SysFileService {

    Logger logger = LoggerFactory.getLogger(getClass());

    private String localDir;

    private Environment environment;

    public Environment getEnvironment() {
        if (this.environment == null) {
            this.environment = SpringBeanUtils.getApplicationContext().getEnvironment();
        }
        return this.environment;
    }

    public String getLocalDir() {
        if (StringUtils.isEmpty(this.localDir)) {
            this.localDir = getEnvironment().getProperty("file.local.dir");
            File file = new File(this.localDir);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        return this.localDir;
    }

    @Override
    public String write(MultipartFile file) throws Exception {
        String id = IdGenerator.generateStringId();
        OutputStream outputStream = null;
        try {
            String newFilePath = this.getLocalDir() + File.separator + id;
            outputStream = new FileOutputStream(newFilePath);
            IOUtils.copy(file.getInputStream(), outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return id;
    }

    @Override
    public byte[] read(String path) throws Exception {
        String _filePath = this.getLocalDir() + File.separator + path;
        return IOUtils.toByteArray(Files.newInputStream(Paths.get(_filePath)));
    }

    @Override
    public void delete(String path) throws Exception {
        String _filePath = this.getLocalDir() + File.separator + path;
        FileUtil.del(_filePath);
    }
}
